<template>
  <el-card class="work-timer-card">
    <div class="timer-content">
      <div class="duration-display">
        <span class="label">今日工作时长</span>
        <span class="value">{{ formattedDuration }}</span>
      </div>
      <el-button
          :type="isRest ? 'success' : 'danger'"
          @click="handleToggle"
          class="control-btn"
      >
        {{ isRest ? '继续工作' : '开始休息' }}
      </el-button>
    </div>
  </el-card>
</template>

<script setup>import { computed, onMounted, onUnmounted } from 'vue'
import {useTimerStore} from "@/store/modules/timerStore.js";

const timerStore = useTimerStore()
let intervalId = null

// 初始化时恢复时间
onMounted(() => {
  // 计算离线期间的时间
  if (!timerStore.isRest && timerStore.lastUpdate) {
    const secondsPassed = Math.floor((Date.now() - timerStore.lastUpdate) / 1000)
    timerStore.totalSeconds += secondsPassed
    timerStore.lastUpdate = Date.now()
  }
  startTimer()
})

// 清理定时器
onUnmounted(() => {
  clearInterval(intervalId)
})

const formattedDuration = computed(() => timerStore.formattedDuration)
const isRest = computed(() => timerStore.isRest)

const handleToggle = () => {
  if (timerStore.isRest) {
    timerStore.startWork()
  } else {
    timerStore.startRest()
  }
}

const startTimer = () => {
  if (!intervalId) {
    intervalId = setInterval(() => {
      timerStore.updateDuration()
    }, 1000)
  }
}
</script>

<style scoped>
.work-timer-card {
  height: 100%;

  .timer-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px;

    .duration-display {
      text-align: center;
      margin-bottom: 24px;

      .label {
        display: block;
        color: #606266;
        font-size: 14px;
        margin-bottom: 8px;
      }

      .value {
        font-size: 32px;
        font-family: monospace;
        color: #303133;
        letter-spacing: 2px;
      }
    }

    .control-btn {
      width: 120px;
      font-weight: 500;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
    }
  }
}
</style>
